package com.xxxx.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.server.Utils.DateUtils;
import com.xxxx.server.mapper.SvaccineMapper;
import com.xxxx.server.mapper.TvaccineMapper;
import com.xxxx.server.pojo.*;
import com.xxxx.server.service.ISvaccineService;
import com.xxxx.server.service.ITvaccineService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 教职工疫苗登记表 前端控制器
 * </p>
 *
 * @author zhoubin
 * @since 2022-06-04
 */
@RestController
@RequestMapping("/vac/tea/")
public class TvaccineController {

    @Autowired
    private ITvaccineService iTvaccineService;
    @Autowired
    private TvaccineMapper tvaccineMapper;

//    @ApiOperation(value = "获取所有辅导员疫苗信息（学校）")
//    @GetMapping("/getall")
//    public List<Ivaccine> getAllIvaccines(){
//        return iIvaccineService.list();
//    }

//    @ApiOperation(value = "根据学院查询辅导员疫苗信息（学院）")
//    @GetMapping("/getbycolege")
//    public List<Ivaccine> getByColegeIdIvaccines(){
//        return iIvaccineService.getByColegeIdIvaccines();
//    }

    @ApiOperation(value = "获取自己的疫苗信息（教职工）")
    @GetMapping("/getone")
    public Tvaccine getOneTvaccine(){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TVid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        queryWrapper.eq("enable",1);
        return iTvaccineService.getOne(queryWrapper);
    }

    @ApiOperation(value = "添加教职工疫苗信息（用户添加）")
    @PostMapping("/post")
    public RespBean addTvaccine(@RequestBody Tvaccine tvaccine){

        QueryWrapper<Tvaccine> wrapper = new QueryWrapper<>();
        wrapper.eq("TVid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        wrapper.eq("enable",1);
        List<Tvaccine> arry = tvaccineMapper.selectList(wrapper);
        for (int i = 0; i < arry.size(); i++) {
            arry.get(i).setEnable(0);
        }
        iTvaccineService.updateBatchById(arry);

        tvaccine.setTVid(((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        tvaccine.setTVdate(LocalDateTime.now());
        tvaccine.setEnable(1);
        if (iTvaccineService.save(tvaccine)){
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败!");
    }

    @ApiOperation(value = "更新教职工疫苗信息（用户更新）")
    @PutMapping("/update")
    public RespBean updateTvaccine(@RequestBody Tvaccine tvaccine){
        tvaccine.setTVid(((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        tvaccine.setEnable(1);
        if (iTvaccineService.updateById(tvaccine)){
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "查询所有的教职工疫苗（分页）")
    @GetMapping("/getPageTvaccine")
    public RespPageBean getTvaccine(@RequestParam(defaultValue = "1") Integer currentPage ,
                                    @RequestParam(defaultValue = "10")Integer size,
                                    Tvaccine tvaccine,
                                    String[] beginDateScope,
                                    String collegename){
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int type=admin.getRoles().get(0).getId();
        int collegeid;
        if(admin.getCollegeid()!=null){
            collegeid = admin.getCollegeid();
        }else{
            collegeid=0;
        }
        return iTvaccineService.getTvaccineByPage(currentPage,size,tvaccine,beginDateScope,type,collegename,collegeid);
    }

    @ApiOperation(value = "登录的教职工疫苗上报是否有效（用户查询）")
    @PutMapping("/isEffective")
    public int isEffectiveTvaccine() throws ParseException {
        QueryWrapper<Tvaccine> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enable",1);
        queryWrapper.eq("TVid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        Tvaccine tvaccine = iTvaccineService.getOne(queryWrapper);
        if(tvaccine == null)
            return 0;

        SimpleDateFormat ft = new SimpleDateFormat("MM-dd hh:mm:ss");
        String nowtime = LocalDateTime.now().toString();

        String startMonth = nowtime.substring(5,7);
        int end = Integer.parseInt (startMonth)+1;

        String endMonth = String.valueOf(end);
        Date startTime = ft.parse(startMonth+"-01 00:00:00");
        Date endTime = ft.parse(endMonth+"-01 00:00:00");

        String time = tvaccine.getTVdate().toString();
        time = time.substring(5,10) + " " + time.substring(11,19);
        Date testTime = ft.parse(time);

        boolean effectiveDate = DateUtils.isEffectiveDate(testTime, startTime, endTime);
        if (effectiveDate) {
            return 1;
        }else {
            return 0;
        }
    }


    @ApiOperation(value = "导出教职工疫苗接种数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportTvaccine(HttpServletResponse response,
                               Tvaccine tvaccine,
                               String[] beginDateScope,
                               String collegename){
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int type=admin.getRoles().get(0).getId();
        int collegeid;
        if(admin.getCollegeid()!=null){
            collegeid = admin.getCollegeid();
        }else{
            collegeid=0;
        }
        List<Tvaccine> list = iTvaccineService.getTnvaccineSeachList(tvaccine,beginDateScope,type,collegename,collegeid);
        ExportParams params = new ExportParams("教职工疫苗接种情况表","教职工疫苗接种情况表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Tvaccine.class, list);
        ServletOutputStream out = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("教职工疫苗接种情况表.xls","UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
